package com.fangmao.jetpack.viewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

/**
 * @ProjectName: wman
 * @Package: com.fangmao.view_model
 * @ClassName: MainViewModel
 * @Description: java类作用描述
 * @Author: wman
 * @CreateDate: 2020/1/6 10:42
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/1/6 10:42
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class MainViewModel extends ViewModel {
    /**
     * 保存状态的SavingStateLiveData
     */
    private SavedStateHandle mSavedStateHandle;
    private static final String KEY_A_TEAM_SCORE = "KEY_A_TEAM_SCORE";
    private static final String KEY_B_TEAM_SCORE = "KEY_B_TEAM_SCORE";
    /**
     * 缓存上一次状态
     */
    private int aBack, bBack;

    public MainViewModel(SavedStateHandle handle) {
        this.mSavedStateHandle = handle;
    }

    public MutableLiveData<Integer> getATeamScore() {
        if (!mSavedStateHandle.contains(KEY_A_TEAM_SCORE)) {
            mSavedStateHandle.set(KEY_A_TEAM_SCORE, 0);
        }
        return mSavedStateHandle.getLiveData(KEY_A_TEAM_SCORE);
    }

    public MutableLiveData<Integer> getBTeamScore() {
        if (!mSavedStateHandle.contains(KEY_B_TEAM_SCORE)) {
            mSavedStateHandle.set(KEY_B_TEAM_SCORE, 0);
        }
        return mSavedStateHandle.getLiveData(KEY_B_TEAM_SCORE);
    }

    public void addATeamScore(int score) {
        backup();
        getATeamScore().setValue(getATeamScore().getValue() + score);
    }

    public void addBTeamScore(int score) {
        backup();
        getBTeamScore().setValue(getBTeamScore().getValue() + score);
    }

    private void backup() {
        aBack = getATeamScore().getValue();
        bBack = getBTeamScore().getValue();
    }

    public void reset() {
        backup();
        mSavedStateHandle.getLiveData(KEY_A_TEAM_SCORE).setValue(0);
        mSavedStateHandle.getLiveData(KEY_B_TEAM_SCORE).setValue(0);
    }

    public void undo() {
        getATeamScore().setValue(aBack);
        getBTeamScore().setValue(bBack);
    }
}
